#!/bin/bash

echo "📋 检查后端环境配置"
echo "=================="

echo ""
echo "1️⃣ 检查当前目录..."
pwd

echo ""
echo "2️⃣ 检查.env文件..."
if [ -f ".env" ]; then
    echo "✅ .env文件存在"
    echo "内容:"
    cat .env
else
    echo "❌ .env文件不存在"
    echo "创建默认.env文件..."
    cat > .env << EOF
DATABASE_URL=postgresql://postgres:aide123456@localhost:5432/aide
JWT_SECRET=aide_jwt_secret_key_change_in_production
JWT_EXPIRES_IN=7d
PORT=5000
EOF
    echo "✅ 已创建.env文件"
fi

echo ""
echo "3️⃣ 检查环境变量..."
echo "DATABASE_URL: $DATABASE_URL"
echo "JWT_SECRET: ${JWT_SECRET:0:10}..."
echo "PORT: $PORT"

echo ""
echo "4️⃣ 检查数据库连接..."
if [ -f "debug-docker-db.js" ]; then
    echo "运行数据库连接测试..."
    node debug-docker-db.js
else
    echo "创建数据库连接测试脚本..."
    cat > test-db-connection.js << 'EOF'
const { Client } = require('pg');
require('dotenv').config();

async function testConnection() {
  console.log('🔍 测试数据库连接...');
  
  const client = new Client({
    connectionString: process.env.DATABASE_URL || 'postgresql://postgres:aide123456@localhost:5432/aide'
  });

  try {
    await client.connect();
    console.log('✅ 数据库连接成功');
    
    const result = await client.query('SELECT version()');
    console.log('📋 PostgreSQL版本:', result.rows[0].version.split(' ')[0] + ' ' + result.rows[0].version.split(' ')[1]);
    
    // 检查数据库是否存在
    const dbCheck = await client.query("SELECT datname FROM pg_database WHERE datname = 'aide'");
    if (dbCheck.rows.length > 0) {
      console.log('✅ aide数据库存在');
    } else {
      console.log('❌ aide数据库不存在');
    }
    
  } catch (error) {
    console.error('❌ 数据库连接失败:', error.message);
    console.log('🔧 可能的解决方案:');
    console.log('1. 检查PostgreSQL容器是否运行: sudo docker ps | grep postgres');
    console.log('2. 检查密码是否正确: aide123456');
    console.log('3. 重新创建容器: ./fix-postgres-connection.sh');
  } finally {
    await client.end();
  }
}

testConnection();
EOF
    
    echo "运行连接测试..."
    node test-db-connection.js
fi

echo ""
echo "5️⃣ 检查依赖..."
echo "检查关键依赖是否安装..."
node -e "
try {
  require('pg');
  console.log('✅ pg (PostgreSQL客户端) 已安装');
} catch(e) {
  console.log('❌ pg 未安装');
}

try {
  require('dotenv');
  console.log('✅ dotenv 已安装');
} catch(e) {
  console.log('❌ dotenv 未安装');
}

try {
  require('express');
  console.log('✅ express 已安装');
} catch(e) {
  console.log('❌ express 未安装');
}
"

echo ""
echo "✅ 环境检查完成！"
